import axiosStatic, { type AxiosError, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import type { App } from 'vue';

const axios = axiosStatic.create({
  baseURL: '/api',
  timeout: 300 * 1000,
});

axios.interceptors.request.use(e => {
  console.error('axios.interceptors.request >>> e =', e);
  return Promise.reject('请求失败');
});

const getErrorMessage = (error: AxiosError<any>) => {
  const response = error.response;
  if (response && response.data) {
    return (response.data as any).errorMessage || '';
  }
  return '';
};

axios.interceptors.response.use(
  (response: AxiosResponse) => {
    return Promise.resolve(response.data);
  },
  (error: AxiosError<any>) => {
    const response = error.response;
    const status = response ? Number(response.status) : -1;
    switch (status) {
      case 500:
        return Promise.reject('服务忙，请稍后再试');
      default:
        return Promise.reject(getErrorMessage(error));
    }
  },
);

export { axios };

export default {
  install: (app: App) => {
    app.config.globalProperties.$axios = axios;
  },
};
